const express = require('express')
const app = express()
app.use(require('cors')())
app.use(express.json())
require('./db/db')(app) // 连接数据库
const assert = require('http-assert')
const fs = require('fs')
const User = require('./models/User')
const authMiddleWare = require('./middleWare/auth')
const resourceMiddleWare = require('./middleWare/resource')
const moment = require('moment')
const router = express.Router({
    mergeParams: true
})
// 获取某个资源
router.get('/:id', async (req, res) => {
    const model = await req.Model.find()
    res.send(model)
})

// 修改资源
router.put('/:id', async (req, res) => {
    const model = await req.Model.findByIdAndUpdate(req.params.id, req.body)
    res.send({
        message: '操作成功'
    })
})

// 删除资源
router.delete('/:id', async (req, res) => {
    const model = await req.Model.findByIdAndDelete(req.params.id)
    res.send({
        message: '操作成功'
    })
})
app.use('/api/rest/:resource', authMiddleWare(), resourceMiddleWare(), router)

// 创建老板
app.post('/api/bosses', authMiddleWare(), async (req, res) => {
    const Boss = require('./models/Boss')
    const mo = await Boss.findOne({
        name: req.body.name,
        username: req.user.username
    })
    if (mo) {
        res.status(422).send('已经存在')
        return
    }
    req.body.username = req.user.username
    const model = await Boss.create(req.body)
    res.send(model)
})
// 获取老板
app.get('/api/bosses', authMiddleWare(), async (req, res) => {
    const Boss = require('./models/Boss')
    const model = await Boss.find().where({
        username: req.user.username
    })
    res.send(model)
})

// 创建商品
app.post('/api/products', authMiddleWare(), async (req, res) => {
    const Product = require('./models/Product')
    const mo = await Product.findOne({
        name: req.body.name,
        bossId: req.body.bossId
    })
    console.log('mo', mo)
    if (mo) {
        res.status(422).send('已经存在')
        return
    }
    const model = await Product.create(req.body)
    res.send(model)
})
// 获取商品
app.get('/api/products/:id', authMiddleWare(), async (req, res) => {
    const Product = require('./models/Product')
    const model = await Product.find().where({
        bossId: req.params.id
    })
    res.send(model)
})

// 创建账单
app.post('/api/bills', authMiddleWare(), async (req, res) => {
    const Bill = require('./models/Bill')
    req.body.userId = req.user._id
    const model = await Bill.create(req.body)
    res.send(model)
})

// 获取今日账单
app.get('/api/todaybills', authMiddleWare(), async (req, res) => {
    const Boss = require('./models/Boss')
    let today = moment(new Date()).format('YYYY-MM-DD')
    let ltDay = moment(new Date()).add(1, 'days').format('YYYY-MM-DD')
    const model = await Boss.find({
        username: req.user.username
    }).populate({
        path: 'tobills',
        match: {
            createTime: {
                $gte: today,
                $lt: ltDay
            }
        }

    }).lean()
    res.send(model)
})
// 获取本月账单
app.get('/api/thismonthbills', authMiddleWare(), async (req, res) => {
    const Boss = require('./models/Boss')
    let firstMonth = moment(new Date()).startOf('month').format('YYYY-MM-DD')
    let lastMonth = moment(new Date()).endOf('month').format('YYYY-MM-DD')
    console.log('firstMonth', firstMonth, lastMonth)
    const model = await Boss.find({
        username: req.user.username
    }).populate({
        path: 'tobills',
        match: {
            createTime: {
                $gte: firstMonth,
                $lte: lastMonth
            }
        }

    }).lean()
    res.send(model)
})

// 获取本月账单
app.post('/api/historybills', authMiddleWare(), async (req, res) => {
    const Boss = require('./models/Boss')
    const Bill = require('./models/Bill')
    const {
        startDate,
        endDate
    } = req.body
    const model = await Bill.find({
        createTime: {
            $gte: startDate,
            $lte: endDate
        }
    })
    console.log('model', model)
    // let firstMonth = moment(new Date()).startOf('month').format('YYYY-MM-DD')
    // let lastMonth = moment(new Date()).endOf('month').format('YYYY-MM-DD')
    // console.log('firstMonth', firstMonth, lastMonth)
    // const model = await Boss.find({
    //     username: req.user.username
    // }).populate({
    //     path: 'tobills',
    //     match: {
    //         createTime: {
    //             $gte: firstMonth,
    //             $lte: lastMonth
    //         }
    //     }

    // }).lean()
    res.send(model)
})



// 注册
app.post('/api/user/register', async (req, res) => {
    const {
        username,
        password
    } = req.body
    const user = await User.findOne({
        username
    })
    assert(!user, 422, '用户名已存在!')
    const data = await User.create({
        username,
        password
    })
    res.send(data)
})
// 登录
app.post('/api/user/login', async (req, res) => {
    const {
        username,
        password
    } = req.body
    const user = await User.findOne({
        username
    }).select('+password')
    assert(user, 422, '用户名不存在!')
    const isValid = require('bcryptjs').compareSync(password, user.password)
    assert(isValid, 423, '密码错误!')
    const secret = await fs.readFileSync('secret.text', 'utf-8')
    const token = require('jsonwebtoken').sign({
        id: user._id
    }, secret)
    res.send({
        token
    })
})


app.listen(3000, () => {
    console.log('服务启动成功:http://localhost:3000')
})